package com.cse.engine.subEngine;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.mutear.ParallelSearcher.utils.IResult;

public abstract class BaseEngine implements Engine {

	protected String engineName;

	public BaseEngine(String engineName) {
		this.engineName = engineName;
	}

	@Override
	public List<IResult> search(String key) {
		// 网络请求，获取 html 代码
		HttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 10000);
		HttpGet httpGet = new HttpGet(perfectUrl(key));
		String html = null;
		HttpResponse httpResponse;
		try {
			httpResponse = httpClient.execute(httpGet);
			int resStatu = httpResponse.getStatusLine().getStatusCode();
			if (resStatu == HttpStatus.SC_OK) {
				HttpEntity httpEntity = httpResponse.getEntity();
				if (httpEntity != null) {
					html = EntityUtils.toString(httpEntity, "utf-8");
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return handleHtml(html);
	}

	/**
	 * 解析 html 代码
	 * 
	 * @param html
	 * @return
	 */
	protected abstract List<IResult> handleHtml(String html);

	protected abstract String perfectUrl(String key);

	/**
	 * 转换关键词</br> 因为 url 中不能有空格，因此将空格转换为逻辑或符号 +
	 * 
	 * @param key
	 * @return
	 */
	protected String convert(String key) {
		String[] words = key.split(" ");
		key = words[0];
		for (int i = 1; i < words.length; i++) {
			key += "+" + words[i];
		}
		return key;
	}

	/**
	 * 中文编码
	 * @param url
	 * @return
	 */
	private String encode(String url) {
		Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
		while (matcher.find()) {
			String tmp = matcher.group();
			try {
				url = url.replaceAll(tmp, URLEncoder.encode(tmp, "gbk"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return url;
	}

}
